<%
' +----------------------------------------------------------------------
' | POPASP [ ASP MVC ]
' +----------------------------------------------------------------------
' | Copyright (c) 2016 http://popasp.com All rights reserved.
' +----------------------------------------------------------------------
' | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
' +----------------------------------------------------------------------
' | Author: popasp <1737025626@qq.com>
' +----------------------------------------------------------------------
Class POPASP_CONTROLLER
	public template
	public waitSecond,jumpUrl,taihom
	private tplShowTime
	
	' 生成验证码
	Public Sub Verify
		P_("VERIFY").output "verify"
	End Sub
	
	'注销对象
	Public Sub Unset( ByRef obj )
		Call POP_MVC.Unset(obj)
	End Sub
	
	'注销对象，可连续操作
	Public Function u( ByRef obj )
		Call POP_MVC.Unset(obj)
		set u = Me
	End Function
	
	'快速生成只有一个键值对的Dictionary对象
	Public Function dict( key ,value )
		dim d
		set d = D_
		if isObject( value ) then
			set d(key) = value
		else
			d(key) = value
		end if
		set dict = d
	end Function

	
	' 请求类型是否为GET
	Function isGet()
		isGet = isTheRequest("get")
	End Function
	
	' 请求类型是否为POST
	Function isPost()
		isPost = isTheRequest("post")
	End Function
	
	' 是否为ajax请求
	Function isAjax()
		if Not isEmpty( server("HTTP_X_REQUESTED_WITH") ) Then
			isAjax = True
		Elseif Not isEmpty( [get]("VAR_AJAX_SUBMIT") ) OR Not isEmpty( Form("VAR_AJAX_SUBMIT") ) Then
			isAjax = True
		Else
			isAjax = False
		End If
		
	End Function
	
	' 页面跳转
	Sub Redirect(args)
		dim url
		url = U_(args)
		Call R_(url)
	End Sub
	

	
	' 根据键名获取 Request.QueryString中的值
	Public Function [get]( key )
		if key="" then
			[get] = Request.QueryString
		else
			[get] = Request.QueryString(key)
		end if
	End Function
	
	' 根据键名获取 Request.Form中的值
	Public Function Form(key)
		if key = "" then
			Form = Request.Form
			exit Function
		end if
		if not isEmpty(Request.Form(key)) Then
			if TypeName(Request.Form(key)) = "IStringList" Then
				Form = CStr( Request.Form(key) )
			Else
				Form = Request.Form(key)
			End If			
		End If
	End Function
	
	' 根据键名获取 Request.Form中的值
	Private Function post( key )
		on error resume next
		if key = "" OR key="-1" then
			set post = POP_MVC.post("")
		else
			set post = POP_MVC.post("")
			if isObject( post(key) ) Then
				set post = post(key)
			else
				post = post(key)
			end if			
		end If
		POP_MVC.ajax err.description
	End Function
	
	'存在则返回Request.ServerVariables的键值，不存在返回Empty
	Public Function var( key )
		var = Request.ServerVariables(key)
	End Function
	
	
	'存在则返回Request.ServerVariables的键值，不存在返回Empty
	Public Function server( key )
		server = Request.ServerVariables(key)
	End Function
	
	' Ajax返回
	' 分配变量时采用的步骤如下
	' set dict = D_		'一定采用如下分配顺序
	' dict(K_) = "data"	
	' dict(K_) = "info"
	' dict(K_) = "status"
	' 或者只传参data
	' 如果data是Recordset，函数会自动处理的
	Public Sub AjaxReturn ( byRef dict ) 		
		on error resume next
		dim args,i,key
		set args = D_
		args("0") = ""		'data
		args("1") = ""		'info
		args("2") = 1		'status		
		
		if isArray( dict ) Then
			for i = 0 to ubound(dict)
				args( CStr(i) ) = dict(i)
			next
		elseif TypeName(dict) = "Dictionary" Then
			if dict.Exists("0") Then
				set args = POP_MVC.dict.Merge(args,dict)
			else
				POP_MVC.dict.edit args,"0",dict
			end if
		Else
			POP_MVC.dict.edit args,"0",dict
		End If
		
		POP_MVC.dict.edit args,"data",args("0")
		POP_MVC.dict.edit args,"info",args("1")
		POP_MVC.dict.edit args,"status",args("2")

		' 0 1 2 这三个键/值对是临时的
		args.Remove("0") : args.Remove("1") : args.Remove("2")
		if TypeName( args("data") ) = "Recordset" Then
			if is_empty( args("data") ) Then
				args("data") = array()
			else 
				args("data") = rs2arr( args("data") )
			end If
		End If
		
		call Response.AddHeader("content-type", "application/json; charset=utf-8")
		Response.Write  Easp.Str.toString(args)
		Response.end
		call unset(dict)
		call unset(args)
		call L_("")
	End Sub
	
	'''
     ' 操作失败后跳转的快捷方法
     ' @param string message 提示信息
     ' @param string jump_url 页面跳转地址
     ' @param mixed ajax 是否为Ajax方式 当数字时指定跳转时间
     ' @return void
	'''
	Sub [Error]( args )
		dim dict,i
		set dict = D_
		dict(0) = ""	'message
		dict(1) = ""	'jump_url
		dict(2) = false	'ajax
		if isArray( args ) Then
			for i = 0 to ubound(args)
				dict(i) = args(i)
			next
		else 
			dict(0) = args
		end If
		message = dict(0) : jump_url = dict(1) : ajax = dict(2)
		set dict = nothing
		call dispatchJump( message , 0, jump_url , ajax )
	End Sub
	
	'''
     ' 操作成功跳转的快捷方法
     ' @param string message 提示信息
     ' @param string jump_url 页面跳转地址
     ' @param mixed ajax 是否为Ajax方式 当数字时指定跳转时间
     ' @return void
	'''
	Sub Success( args )
		dim dict,i
		set dict = D_
		dict(0) = ""	'message
		dict(1) = ""	'jump_url
		dict(2) = false	'ajax
		if isArray( args ) Then
			for i = 0 to ubound(args)
				dict(i) = args(i)
			next
		else 
			dict(0) = args
		end If
		message = dict(0) : jump_url = dict(1) : ajax = dict(2)
		set dict = nothing
		call dispatchJump( message , 1, jump_url , ajax )
	End Sub
	
	
    '''
     ' 默认跳转操作 支持错误导向和正确跳转
     ' 调用模板显示 默认为public目录下面的success页面
     ' 提示页面为可配置 支持模板标签
     ' @param string message 提示信息
     ' @param Boolean status 状态
     ' @param string jumpUrl 页面跳转地址
     ' @param mixed ajax 是否为Ajax方式 当数字时指定跳转时间
	'''
    Private sub dispatchJump(message,status,jump_url,ajax) 
		on error resume next
		dim dict,dir,tpl,waitSecond,sUrl,sRand
		template.caching = 0
		template.layout_on = False
		template.session_length = 2048
		template.left_delimiter = "{"
		template.right_delimiter = "}"
		template.use_ctrl_tpl = False
		template.tpl_suffix = ".html"
        if true = ajax OR isAjax() then 'AJAX提交
			set dict = D_
			dict("0")   =   ""		
			dict("1")	=   message
			dict("2")	=   status
			call ajaxReturn(dict)  
			exit sub
        End If
		'ajax所代表的是等待秒数
		if is_numeric( ajax ) Then
			waitSecond = ajax
			call assign("waitSecond",waitSecond)
		End if
		
		if not is_empty( jump_url ) Then
			call assign( "jumpUrl" , jump_url )
		End If

        ' 提示标题
		if is_empty(status) Then
			call assign( "msgTitle" , "操作失败" )
		Else
			call assign( "msgTitle" , "操作成功" )
		End If
		
        '如果设置了关闭窗口，则提示完毕后自动关闭窗口
		if not is_empty([get]("closeWin")) Then
			call assign( "jumpUrl" , "javascript:window.close();" )
		End If

		call assign("status",status)	'状态

		
        '保证输出不受静态缓存影响
        call C_( array("HTML_CACHE_ON",false) )
		
		
		if not is_empty( status ) Then	'操作正确时的提示
			call assign("message",message)	'提示信息
			
			if  isEmpty( waitSecond ) Then
				call assign("waitSecond",3)	'成功操作后默认停留1秒
			else 
				call assign("waitSecond",waitSecond)	'成功操作后默认停留1秒
			End If

			if isEmpty( jumpUrl ) and is_empty(jump_url) Then
				
				'开启参数C_("TMPL_SUCCESS_URL_NOCACHE")，将会在URL中添加C_("URL_NOCACHE_ARGUMENT")=随机数，如POPASP_NOCACHE_LABEL=671986
				if Not is_empty( C_("TMPL_SUCCESS_URL_NOCACHE") ) Then	
					sRand = int(rnd() * 1000000)	'随机数，如671986
					if Request.QueryString = "" then
						call assign("jumpUrl", server("HTTP_REFERER") & "?" & C_("URL_NOCACHE_ARGUMENT") & "=" & sRand )
					else
						sUrl = server("HTTP_REFERER")	'跳转前的URL地址					
						sUrl = POP_MVC.String.reg_replace( sUrl,"" , "(&|\?)" &  C_("URL_NOCACHE_ARGUMENT") & "=" & "[^&\?]+" , "ig" )	'删除原来的防缓存参数
						if POP_MVC.String.Exists( sUrl , "?" ) Then	'如果URL地址中有?，则添加 &POPASP_NOCACHE_LABEL=671986
							call assign("jumpUrl", sUrl & "&" & C_("URL_NOCACHE_ARGUMENT") & "=" & sRand )
						else	'如果无?，则添加 ?POPASP_NOCACHE_LABEL=671986
							call assign("jumpUrl", sUrl & "?" & C_("URL_NOCACHE_ARGUMENT") & "=" & sRand )
						end if					
					end if
				else
					call assign("jumpUrl", server("HTTP_REFERER"))
				end if
			End If
			
			if is_empty(C_("TMPL_ACTION_SUCCESS")) Then
				dir = POP_MVC.mvc_dir & "Tpl/"
				tpl = "dispatch_jump"
			else 
				'dir = Replace( C_("TMPL_ACTION_SUCCESS") , "\" ,"/" )
				'dir = left(dir,inStrRev( dir,"/" ))
				'tpl = right(dir,len(dir) - inStrRev( dir,"/" ))
				tpl = C_("TMPL_ACTION_SUCCESS")
			End If	
			template.template_dir = dir	
			call display0( tpl ,"")
		Else	'操作错误时的提示
			call assign("error",message)	'提示信息
			
			if  isEmpty( waitSecond ) Then	
				call assign("waitSecond",3)	'失败操作后默认停留3秒
			else 
				call assign("waitSecond",waitSecond)	'失败操作后默认停留1秒
			End If
			
			if isEmpty( jumpUrl ) and is_empty(jump_url) Then
				call assign("jumpUrl", "javascript:history.back(-1);" )
			End If
			
			if C_("TMPL_ACTION_ERROR") = "" Then
				dir = POP_MVC.mvc_dir & "Tpl/"
				tpl = "dispatch_jump"
			else 
				'dir = Replace( C_("TMPL_ACTION_ERROR") , "\" ,"/" )
				'dir = left(dir,inStrRev( dir,"/" ))
				'tpl = right(dir,len(dir) - inStrRev( dir,"/" ))
				tpl = C_("TMPL_ACTION_ERROR")
			End If
			template.template_dir = dir			
			call display_1( tpl ,"" )			
		End If
		POP_MVC.quit
    End Sub
	
	Public Sub echo( str )
		Response.Write str
	End Sub
	
	Public Sub setTplConfig( key, value )
		if isNumeric(value) then
			Execute "template." & key & " = " & value
		else
			Execute "template." & key & " = """ & value & """"
		end if
	End Sub
	
	Public Property Get [Load](ByVal tpl)
		template.Load( tpl )
		set taihom = template.taihom
	End Property
	
	Public Property Let d(ByVal strTag,ByVal strVal)
		taihom.d(strTag) = strVal
	end property
	
	public Sub assign( tpl_var, value )	
		Call template.assign(tpl_var,value)		
	End Sub
	
	public Sub mem_assign( key, value )	
		Call template.mem_assign(key,value)		
	End Sub	
	
	public Function mem_cached( key )	
		mem_cached = template.mem_cached(key)		
	End Function	
	
	Public Function is_temped( byVal tpl )
		is_temped = template.is_temped( tpl )
	End Function
	
	Public function is_cached( byval tpl , byval id)	
		is_cached = template.is_cached(tpl,id)
	End Function
	
	Public Sub Display ( options )		
		call template.Display(options)		
	end Sub
	
	Public Property Get Show
		call template.show
	end Property
	
	Public Sub Display0 ( tpl , id ) 
		call template.Display0(tpl , id)
		'Response.write "页面执行时间："&FormatNumber((timer()-start_time__)*1000,3,-1,0,0)&"毫秒"
	End Sub
	
	Public Sub Display_1( ByRef tpl , ByRef id )
		call template.Display_1(tpl,id)
		'Response.write "页面执行时间："&FormatNumber((timer()-start_time__)*1000,3,-1,0,0)&"毫秒"
	End Sub
	
	Public Sub Display1( ByRef tpl , ByRef id )
		call template.Display1(tpl,id)
		'Response.write "页面执行时间："&FormatNumber((timer()-start_time__)*1000,3,-1,0,0)&"毫秒"
	End Sub
	
	Private Sub Class_Initialize	
		set template = P_( "POPASP_TEMPLATE" )
	End Sub
	
	Private Sub Class_Terminate
		if isObject(template) Then
			set template = nothing
		End If		
	End Sub
	
	' 将Recordset结果集转化数组，数组中的每个值为每行记录，且为Dictionary类型
	Public Function rs2arr(rs)
		dim i,k,dict,arr()
		for k = 1 to rs.pageSize		
			if not rs.BOF and not rs.EOF Then
				redim preserve arr(k-1)
				set dict = D_
				for i = 0 to rs.fields.count-1
					dict( rs.Fields(i).Name ) = rs.Fields(i).Value 
				next
				
				if dict.Count > 0 Then
					set arr(k-1) = dict
				end if
				rs.moveNext
			end If
		next
		rs2arr = arr
		set dict = nothing
	End Function
	
	' 将Recordset结果集转化成Dictionary，每行记录的键名均为数字类型，且为Dictionary类型
	Public Function rs2dict(rs)
		set rs2dict = POP_MVC.rs2dict(rs)
	End Function
	
	' 将Recordset结果集转化成用于前端显示的json字符串
	Public function rs2json(rs)
		rs2json = Easp.Str.toString(rs)
		rs2json = mid(rs2json,inStr(rs2json,"["),inStrRev(rs2json,"]")-inStr(rs2json,"[")+1)
	End function
	
	' 中止程序
	Public Sub [exit]()
		Response.End
	End Sub
	
	Private Function isTheRequest(key)
		isTheRequest = ( LCase(key) = LCase(getRequestMethod))
	End Function
	
	' 获取请求类型
	Private Function getRequestMethod()
		getRequestMethod = Request.ServerVariables("REQUEST_METHOD")
	End Function	
	
End Class
%>